﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core;
namespace Admin.NET.Application;

/// <summary>
/// 盘点单表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SysstocktakingorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Sysstocktakingorder> _sysstocktakingorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SysstocktakingorderService(SqlSugarRepository<Sysstocktakingorder> sysstocktakingorderRep, ISqlSugarClient sqlSugarClient)
    {
        _sysstocktakingorderRep = sysstocktakingorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询盘点单表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询盘点单表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SysstocktakingorderOutput>> Page(PageSysstocktakingorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        
        // 通过ID进行联查(WarehouseName字段存储的是仓库ID的字符串形式)
        var query = _sysstocktakingorderRep.AsQueryable()
            .LeftJoin<WarehouseModel>((st, wh) => 
                SqlFunc.ToString(wh.Id) == st.WarehouseName && wh.IsDelete == false)
            .LeftJoin<GoodsModel>((st, wh, gd) => 
                st.GoodsName == gd.GoodsCode && gd.IsDelete == false)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), (st, wh, gd) => st.Code.Contains(input.Keyword) || st.InventoryResult.Contains(input.Keyword) || st.WarehouseName.Contains(input.Keyword) || st.StockTakingType.Contains(input.Keyword) || st.GoodsName.Contains(input.Keyword) || st.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), (st, wh, gd) => st.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryResult), (st, wh, gd) => st.InventoryResult.Contains(input.InventoryResult.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehouseName), (st, wh, gd) => st.WarehouseName.Contains(input.WarehouseName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StockTakingType), (st, wh, gd) => st.StockTakingType.Contains(input.StockTakingType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), (st, wh, gd) => st.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), (st, wh, gd) => st.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.StartTimeRange?.Length == 2, (st, wh, gd) => st.StartTime >= input.StartTimeRange[0] && st.StartTime <= input.StartTimeRange[1])
            .WhereIF(input.EndTimeRange?.Length == 2, (st, wh, gd) => st.EndTime >= input.EndTimeRange[0] && st.EndTime <= input.EndTimeRange[1])
            .WhereIF(input.OutStatus.HasValue, (st, wh, gd) => st.OutStatus == input.OutStatus.Value)
            .WhereIF(input.InStatus.HasValue, (st, wh, gd) => st.InStatus == input.InStatus.Value)
            .WhereIF(input.Quantity != null, (st, wh, gd) => st.Quantity == input.Quantity)
            .WhereIF(input.DocumentStatus.HasValue, (st, wh, gd) => st.DocumentStatus == input.DocumentStatus.Value)
            .WhereIF(input.DeleteTimeRange?.Length == 2, (st, wh, gd) => st.DeleteTime >= input.DeleteTimeRange[0] && st.DeleteTime <= input.DeleteTimeRange[1])
            .Select((st, wh, gd) => new SysstocktakingorderOutput
            {
                Id = st.Id,
                Code = st.Code,
                InventoryResult = st.InventoryResult,
                WarehouseName = st.WarehouseName,
                StockTakingType = st.StockTakingType,
                StartTime = st.StartTime,
                EndTime = st.EndTime,
                OutStatus = st.OutStatus,
                InStatus = st.InStatus,
                GoodsName = st.GoodsName,
                Quantity = st.Quantity,
                ProfitQuantity = st.ProfitQuantity,
                LossQuantity = st.LossQuantity,
                ProfitAmount = st.ProfitAmount,
                LossAmount = st.LossAmount,
                DocumentStatus = st.DocumentStatus,
                Remark = st.Remark,
                TenantId = st.TenantId,
                OrgId = st.OrgId,
                IsDelete = st.IsDelete,
                DeleteTime = st.DeleteTime,
                CreateTime = st.CreateTime,
                UpdateTime = st.UpdateTime,
                CreateUserId = st.CreateUserId,
                CreateUserName = st.CreateUserName,
                UpdateUserId = st.UpdateUserId,
                UpdateUserName = st.UpdateUserName
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取盘点单表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取盘点单表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Sysstocktakingorder> Detail([FromQuery] QueryByIdSysstocktakingorderInput input)
    {
        return await _sysstocktakingorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加盘点单表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加盘点单表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSysstocktakingorderInput input)
    {
        var entity = input.Adapt<Sysstocktakingorder>();
        ValidateAndSetInventoryResult(entity);
        return await _sysstocktakingorderRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新盘点单表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新盘点单表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSysstocktakingorderInput input)
    {
        var entity = input.Adapt<Sysstocktakingorder>();
        ValidateAndSetInventoryResult(entity);
        await _sysstocktakingorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除盘点单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除盘点单表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSysstocktakingorderInput input)
    {
        var entity = await _sysstocktakingorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _sysstocktakingorderRep.FakeDeleteAsync(entity);   //假删除
        //await _sysstocktakingorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除盘点单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除盘点单表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSysstocktakingorderInput> input)
    {
        var exp = Expressionable.Create<Sysstocktakingorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _sysstocktakingorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _sysstocktakingorderRep.FakeDeleteAsync(list);   //假删除
        //return await _sysstocktakingorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出盘点单表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出盘点单表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSysstocktakingorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSysstocktakingorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "盘点单表导出记录");
    }
    
    /// <summary>
    /// 下载盘点单表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载盘点单表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSysstocktakingorderOutput>(), "盘点单表导入模板");
    }
    
    /// <summary>
    /// 验证盘点数据并设置盘点结果状态
    /// </summary>
    /// <param name="entity"></param>
    private void ValidateAndSetInventoryResult(Sysstocktakingorder entity)
    {
        var quantity = entity.Quantity ?? 0;
        var profitQuantity = entity.ProfitQuantity ?? 0;
        var lossQuantity = entity.LossQuantity ?? 0;
        var profitAmount = entity.ProfitAmount ?? 0;
        var lossAmount = entity.LossAmount ?? 0;

        // 验证盘盈数量不能超过盘点数量
        if (profitQuantity > quantity)
        {
            throw Oops.Oh("盘盈数量不能超过盘点数量");
        }

        // 验证盘亏数量不能超过盘点数量
        if (lossQuantity > quantity)
        {
            throw Oops.Oh("盘亏数量不能超过盘点数量");
        }

        // 验证盘盈和盘亏不能同时存在
        bool hasProfitData = profitQuantity > 0 || profitAmount > 0;
        bool hasLossData = lossQuantity > 0 || lossAmount > 0;

        if (hasProfitData && hasLossData)
        {
            throw Oops.Oh("盘盈数量与金额和盘亏数量与金额不能同时存在");
        }

        // 根据数据设置盘点结果状态
        if (hasProfitData)
        {
            // 有盘盈数据，设置为"有盘盈"
            entity.InventoryResult = "有盘盈";
            // 清空盘亏相关数据
            entity.LossQuantity = null;
            entity.LossAmount = null;
        }
        else if (hasLossData)
        {
            // 有盘亏数据，设置为"有盘亏"
            entity.InventoryResult = "有盘亏";
            // 清空盘盈相关数据
            entity.ProfitQuantity = null;
            entity.ProfitAmount = null;
        }
        else
        {
            // 没有盘盈也没有盘亏，设置为"草稿"
            entity.InventoryResult = "草稿";
            // 清空所有盘盈盘亏数据
            entity.ProfitQuantity = null;
            entity.ProfitAmount = null;
            entity.LossQuantity = null;
            entity.LossAmount = null;
        }
    }

    private static readonly object _sysstocktakingorderImportLock = new object();
    /// <summary>
    /// 导入盘点单表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入盘点单表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_sysstocktakingorderImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSysstocktakingorderInput, Sysstocktakingorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.OutStatus == null){
                            x.Error = "出库状态不能为空";
                            return false;
                        }
                        if (x.InStatus == null){
                            x.Error = "入库状态不能为空";
                            return false;
                        }
                        if (x.DocumentStatus == null){
                            x.Error = "单据状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Sysstocktakingorder>>();
                    
                    // 对每条数据进行验证并设置盘点结果
                    foreach (var row in rows)
                    {
                        try
                        {
                            ValidateAndSetInventoryResult(row);
                        }
                        catch (Exception ex)
                        {
                            // 如果验证失败，标记错误但不中断整个导入过程
                            continue;
                        }
                    }
                    
                    var storageable = _sysstocktakingorderRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "盘点单号不能为空")
                        .SplitError(it => it.Item.Code?.Length > 64, "盘点单号长度不能超过64个字符")
                        .SplitError(it => it.Item.InventoryResult?.Length > 32, "盘点结果长度不能超过32个字符")
                        .SplitError(it => it.Item.WarehouseName?.Length > 64, "仓库名称长度不能超过64个字符")
                        .SplitError(it => it.Item.StockTakingType?.Length > 32, "盘点类型长度不能超过32个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 512, "盘点货品长度不能超过512个字符")
                        .SplitError(it => it.Item.Remark?.Length > 512, "备注长度不能超过512个字符")
                        .SplitError(it => (it.Item.ProfitQuantity ?? 0) > (it.Item.Quantity ?? 0), "盘盈数量不能超过盘点数量")
                        .SplitError(it => (it.Item.LossQuantity ?? 0) > (it.Item.Quantity ?? 0), "盘亏数量不能超过盘点数量")
                        .SplitError(it => ((it.Item.ProfitQuantity ?? 0) > 0 || (it.Item.ProfitAmount ?? 0) > 0) && ((it.Item.LossQuantity ?? 0) > 0 || (it.Item.LossAmount ?? 0) > 0), "盘盈数量与金额和盘亏数量与金额不能同时存在")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.InventoryResult,
                        it.WarehouseName,
                        it.StockTakingType,
                        it.StartTime,
                        it.EndTime,
                        it.OutStatus,
                        it.InStatus,
                        it.GoodsName,
                        it.Quantity,
                        it.ProfitQuantity,
                        it.LossQuantity,
                        it.ProfitAmount,
                        it.LossAmount,
                        it.DocumentStatus,
                        it.Remark,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
